//
//  BSLRevealViewController.m
//  demo
//
//  Created by RYAN on 15/7/16.
//
//

#import "BSLRevealViewController.h"
#import "BSLGalleryHelper.h"
#import "BSLGalleryPlugin.h"

#define K_SECTION_INSECT 3 

#define K_UNCHOOSE_VIEW_TAG 101
#define K_CHOOSE_VIEW_TAG 102

#define K_MAX_SCALE 1.8
@interface BSLRevealViewCell : UICollectionViewCell<UIScrollViewDelegate>

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIScrollView *scrollView;

@end

@implementation BSLRevealViewCell

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    
    if (self) {
        UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        _imageView = iv;
        
        _scrollView = [[UIScrollView alloc] initWithFrame:iv.frame];
        self.scrollView.delegate = self;
        self.scrollView.maximumZoomScale = K_MAX_SCALE;
        [self.scrollView addSubview:iv];
        [self.contentView addSubview:self.scrollView];
    }
    
    return self;
}

- (void)setDataWithAsset:(BSLAsset *)asset{
    UIImage *fullResolution = [asset fullResolutionImage];
    CGSize size = fullResolution.size;
    [self.scrollView setZoomScale:self.scrollView.minimumZoomScale];
    
    if (size.height / size.width > 3) {
        float scaleX = self.frame.size.width / size.width;
        float imgHeight = size.height * scaleX;
        [self.scrollView setContentSize:CGSizeMake(self.contentView.frame.size.width, imgHeight)];
        [self.imageView setFrame:CGRectMake(0, 0, self.contentView.frame.size.width, imgHeight)];
        [self.imageView setImage:fullResolution];
    }
    
    else{
        [self.imageView setFrame:self.contentView.frame];
        [self.scrollView setContentSize:CGSizeMake(self.contentView.frame.size.width, self.contentView.frame.size.height)];
        
        UIImage *image = [asset fullScreenImage];
        CGRect scaleOriginRect;
        
        if (image)
        {
            self.imageView.image = image;
            CGSize imgSize = image.size;
            
            //判断首先缩放的值
            float scaleX = self.frame.size.width/imgSize.width;
            float scaleY = self.frame.size.height/imgSize.height;
            
            //倍数小的，先到边缘
            
            if (scaleX > scaleY)
            {
                //Y方向先到边缘
                float imgViewWidth = imgSize.width*scaleY;
                //            self.maximumZoomScale = self.frame.size.width/imgViewWidth;
                scaleOriginRect = (CGRect){self.frame.size.width/2-imgViewWidth/2,0,imgViewWidth,self.frame.size.height};
            }
            else
            {
                //X先到边缘
                float imgViewHeight = imgSize.height*scaleX;
                //            self.maximumZoomScale = self.frame.size.height/imgViewHeight;
                scaleOriginRect = (CGRect){0,self.frame.size.height/2-imgViewHeight/2,self.frame.size.width,imgViewHeight};
            }
        }
        
        [self.imageView setFrame:scaleOriginRect];
    }
}

#pragma UIScrollViewDelegate
- (UIImageView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.imageView;
}

@end

@interface BSLRevealViewController (){
    CGPoint startContentOffset;
    NSInteger currentIndexSection;
}

@property (nonatomic, strong) UIView *myNavigationBar;
@property (nonatomic, strong) UIView *myToolBar;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *assets;
@property (nonatomic, assign) BOOL isNavToolBarHidden;

@property (nonatomic, assign) NSInteger screenWidth;

@property BSLAsset *currentAsset;

@end

@implementation BSLRevealViewController

- (id)initWithAssets:(NSMutableArray *)assets{
    self = [super init];
    
    if (self) {
        self.assets = assets;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    [UIApplication sharedApplication].statusBarHidden = YES;
    if ([self respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
        [self prefersStatusBarHidden];
    }
    
    [self.navigationController setNavigationBarHidden:YES];
    [self.navigationController setToolbarHidden:YES];
    
    self.screenWidth = self.view.bounds.size.width;
    [self setupCollectionView];
    [self setupMenu];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.currentAsset = [self.assets objectAtIndex:0];
    [self setNavChosenStatus:self.currentAsset.isUserChosen];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self setCellRasterize:NO inSection:0];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)prefersStatusBarHidden{
    return YES;
}

- (void)setupMenu{
    _myNavigationBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
    [self.myNavigationBar setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.4]];
    
    UIImage *img = [UIImage imageNamed:@"backBtn"];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 5, 34, 34)];
    [imageView setImage:img];
    [self.myNavigationBar addSubview:imageView];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setFrame:CGRectMake(0, 0, 70, 44)];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [self.myNavigationBar addSubview:backBtn];
    
    UIImage *unchoose_img = [UIImage imageNamed:@"un_choose_photo"];
    UIImageView *unchoose_iv = [[UIImageView alloc] initWithImage:unchoose_img];
    [unchoose_iv setImage:unchoose_img];
    [unchoose_iv setFrame:CGRectMake(self.view.bounds.size.width - unchoose_img.size.width - 10, 0.5 * (self.myNavigationBar.frame.size.height - unchoose_img.size.height), unchoose_img.size.width, unchoose_img.size.height)];
    unchoose_iv.tag = K_UNCHOOSE_VIEW_TAG;
    [unchoose_iv setHidden:YES];
    [self.myNavigationBar addSubview:unchoose_iv];
    
    UIImage *choose_img = [UIImage imageNamed:@"did_choose_photo"];
    UIImageView *choose_iv = [[UIImageView alloc] initWithFrame:unchoose_iv.frame];
    [choose_iv setImage:choose_img];
    choose_iv.tag = K_CHOOSE_VIEW_TAG;
    [self.myNavigationBar addSubview:choose_iv];
    
    UIButton *chooseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [chooseBtn setFrame:CGRectMake(self.view.bounds.size.width - 70, 0, 70, 44)];
    [chooseBtn addTarget:self action:@selector(updateMenu) forControlEvents:UIControlEventTouchUpInside];
    [self.myNavigationBar addSubview:chooseBtn];
    
    [self.view addSubview:self.myNavigationBar];
    
    _myToolBar = [[UIView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 44, self.view.bounds.size.width, 44)];
    [self.myToolBar setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.4]];
    UIButton *finishBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [finishBtn setTitle:@"完成" forState:UIControlStateNormal];
    [finishBtn setTitleColor:[UIColor colorWithRed:126/255.0 green:211/255.0 blue:33/255.0 alpha:1] forState:UIControlStateNormal];
    [finishBtn setFrame:CGRectMake(self.myToolBar.frame.size.width - 70, 0, 70, self.myToolBar.frame.size.height)];
    [finishBtn.titleLabel setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:17]];
    [finishBtn addTarget:self action:@selector(finish) forControlEvents:UIControlEventTouchUpInside];
    [self.myToolBar addSubview:finishBtn];
    
    [self.view addSubview:self.myToolBar];
}

- (void)back{
    [self.navigationController setNavigationBarHidden:YES];
    [self.navigationController popViewControllerAnimated:[BSLGalleryHelper shareInatance].isAnimated];
}

- (void)updateMenu{
    self.currentAsset.isUserChosen = !self.currentAsset.isUserChosen;
    [self setNavChosenStatus:self.currentAsset.isUserChosen];
}

- (void)setNavChosenStatus:(BOOL)isUserChosen{
    UIView *chooseV = [self.myNavigationBar viewWithTag:K_CHOOSE_VIEW_TAG];
    UIView *unchooseV = [self.myNavigationBar viewWithTag:K_UNCHOOSE_VIEW_TAG];
    [chooseV setHidden:!isUserChosen];
    [unchooseV setHidden:isUserChosen];
}

- (void)finish{
    for (int i=0; i<self.assets.count; i++) {
        BSLAsset *asset = [self.assets objectAtIndex:i];
        if (!asset.isUserChosen) {
            [self.assets removeObject:asset];
        }
    }
    
    NSMutableArray *libraryPaths = [[BSLGalleryHelper shareInatance] saveToLibrary:self.assets];
    NSString *errorMessage = nil;
    if (!libraryPaths || libraryPaths.count == 0) {
        errorMessage = @"select no images";
    }
    
    [(GalleryNavigationController *)self.navigationController dismiss:libraryPaths errorMessage:errorMessage];
}

- (void)setCellRasterize:(BOOL)shouldRasterize inSection:(NSInteger)section{
    self.currentAsset = [self.assets objectAtIndex:section];
    
    BSLRevealViewCell *cell = (BSLRevealViewCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:section]];
    cell.imageView.layer.shouldRasterize = shouldRasterize;
}

- (void)setupCollectionView{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    [layout setMinimumLineSpacing:0];
    [layout setSectionInset:UIEdgeInsetsMake(K_SECTION_INSECT, K_SECTION_INSECT, K_SECTION_INSECT, K_SECTION_INSECT)];
    
    [layout setItemSize:CGSizeMake(self.view.bounds.size.width - K_SECTION_INSECT - K_SECTION_INSECT, self.view.bounds.size.height - K_SECTION_INSECT - K_SECTION_INSECT)];
    
    UICollectionView *view = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    _collectionView = view;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[BSLRevealViewCell class] forCellWithReuseIdentifier:@"CELL"];
    self.collectionView.bounces = YES;
    self.collectionView.pagingEnabled = YES;
    [self.view addSubview:self.collectionView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureHandle:)];
    [tap setNumberOfTouchesRequired:1];
    [self.collectionView addGestureRecognizer:tap];
}

- (void)tapGestureHandle:(UITapGestureRecognizer *)recognizer{
//    NSLog(@"tap");
    self.isNavToolBarHidden = !self.isNavToolBarHidden;
    [self.myNavigationBar setHidden:self.isNavToolBarHidden];
    [self.myToolBar setHidden:self.isNavToolBarHidden];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - UICollectionView
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.assets.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 1;
}

- (BSLRevealViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    BSLRevealViewCell *cell = (BSLRevealViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
    cell.imageView.layer.shouldRasterize = YES;

    BSLAsset *asset = [self.assets objectAtIndex:indexPath.section];
    [cell setDataWithAsset:asset];
    
    return cell;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    startContentOffset = scrollView.contentOffset;
    currentIndexSection = (NSInteger)startContentOffset.x / self.screenWidth;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    CGPoint point = scrollView.contentOffset;
    NSInteger section = (NSInteger)point.x / self.screenWidth;
    [self setCellRasterize:NO inSection:section];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint currentContentOffset = scrollView.contentOffset;
   
    if (currentContentOffset.x > startContentOffset.x - self.screenWidth * 0.5 && currentContentOffset.x < startContentOffset.x + self.screenWidth * 0.5) {
        BSLAsset *asset = [self.assets objectAtIndex:currentIndexSection];
        [self setNavChosenStatus:asset.isUserChosen];
    }
    
    else if (currentContentOffset.x < startContentOffset.x - self.screenWidth * 0.5 && currentIndexSection - 1 >= 0){
        
        BSLAsset *asset = [self.assets objectAtIndex:currentIndexSection - 1];
        [self setNavChosenStatus:asset.isUserChosen];
    }
    
    else if (currentContentOffset.x > startContentOffset.x + self.screenWidth * 0.5 && currentIndexSection + 1 <= self.assets.count){
        
        BSLAsset *asset = [self.assets objectAtIndex:currentIndexSection + 1];
        [self setNavChosenStatus:asset.isUserChosen];
    }
}

@end
